package logic

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
	"vip_video/configx"
	"vip_video/internal"
	"vip_video/internal/library"
	"vip_video/models"
)

type UserLogic struct {
	db     *sqlx.DB
	config *configx.Config
	_ctx   *gin.Context
}

func NewUserLogic(db *sqlx.DB) *UserLogic {
	return &UserLogic{
		db: db,
	}
}

func (ul *UserLogic) WithConfig(config *configx.Config) *UserLogic {
	ul.config = config
	return ul
}

func (ul *UserLogic) WithCtx(ctx *gin.Context) *UserLogic {
	ul._ctx = ctx
	return ul
}

// MobileLogin 手机号码登录
func (ul *UserLogic) MobileLogin(mobile string, captcha string) (gin.H, error) {
	//todo 验证验证码是否正确
	//查询用户
	var user models.UserModel
	err := ul.db.Get(&user, "select id,nickname,mobile,avatar,status,prevtime,logintime from fa_user where mobile=? limit 1;", mobile)
	auth := library.AuthLibraryInstance(ul.db).WithConfig(ul.config).WithGinCtx(ul._ctx)
	var ret error
	if err == nil {
		if user.Status != models.STATUS_NORMAL {
			return nil, errors.New("您已被禁用")
		}
		ret = auth.Direct(user.Id)
	} else {
		ret = auth.Register(mobile, internal.RandStr(30), map[string]any{})
	}
	if ret != nil {
		return nil, ret
	}
	return auth.GetUserInfo(), nil
}
